<template>
	<view class="container" style="height: 100vh;overflow: hidden;">			
		<view class="dis-flex">
			<view class="user-info">
				<view class="user-name">你好,{{userInfo?userInfo.user_info.nickname:''}}</view>
				<view class="user-role" v-if="showRole!=''">{{showRole}}</view>			
			</view>
			<view @click="navTo()">签到规则</view>
		</view>
		
		<view class="dis-two-flex">
			<view class="turn-s">
				<view class="flex1">累计出勤课节</view>
				<view>{{had}}</view>			
			</view>
			<view class="turn-s">
				<view class="flex1">累计缺勤课节</view>
				<view>{{absence}}</view>			
			</view>
		</view>
		
		<view class="dis-flex" style="flex-direction: column;height: 69%;">
			<view style="display: flex;width: 100%;">
				<view class="today">今日课程</view>
				<view class="course-name">
					<view v-if="course_range.length==0">无<text class="cell-icon yticon icon-xia"  style="font-size: 26rpx;color:#999999"></text></view>
					
					<uni-data-select v-else @change="changeCourse"  v-model="course_section_selected" :clear="false" :placeholder="_selectPlace" :localdata="course_range"></uni-data-select>
				</view>
			</view>
			
			<view v-if="course_range.length>0" style="width: 100%;">
				<view class="sign-column">
					<view class="flex1">上课时间  {{currentItem.begin_time}}-{{currentItem.end_time}}</view>
					<view class="sign-color">{{currentItem.sign_str1}}</view>
				</view>
				<view style="display: flex;justify-content: center;" v-if="currentItem.can_sign1">
					<view class="yuan" @click="signClick()" :class="{'activeColor': is_entrance_range&&currentItem.can_sign1&&is_duration}">
						<view class="sign-current">{{sign_current}}</view>
						<view class="sign-current-time">{{current_time}}</view>
					</view>
				</view>
				
				<view class="sign-status" v-if="currentItem.can_sign1">
					<view style="display: flex;width:100%;flex-direction: column;justify-content: center;">
						<!-- <text v-if="is_entrance_range" class="cell-icon yticon icon-entrance"></text>
						<text v-else class="cell-icon yticon icon-entrance-no"></text> -->
							<view style="display: flex;justify-content: center;">
								<image v-if="is_entrance_range" src="/static/temp/entrance.png" style="width: 40rpx;height: 40rpx"></image>
								<image v-else src="/static/temp/entrance-no.png" style="width: 40rpx;height: 40rpx"></image>
								<view style="margin-left: 20rpx;font-size: 28rpx;">{{entrance_tip}}  </view>
							</view>
							<view style="font-size: 28rpx;text-align: center;margin-top: 20rpx;">{{currentItem.campus_info.address}}</view>
						
						
					</view>
				</view>
			</view>
			<view v-else class="no-course">暂无课程</view>
	
		</view>
		
	</view>
</template>

<script>
	import { mapState } from 'vuex';  
	import Api from '@/common/api';
	export default {
		
		data() {
			return {
				_selectPlace:'请选择需要签到的课程',//无
				course_section_selected:0,
				course_range:[],
				sign_current:'非签到时间',
				current_time:'',
				timer: null, // 定时器
				entrance_tip:'未进入签到范围',
				distence:200,
				is_entrance_range:false,//是否进入签到范围
				currentTimeSecond:0,
				currentItem:{},
				had:0,
				absence:0,
				need_update:false,
				is_duration:false
			};
		},
		
		onLoad() {
			
		},
		beforeCreate(){
			
		},
		beforeDestroy(){
			uni.stopLocationUpdate();
			this.clearTimer();
		},
		onHide(){
			uni.stopLocationUpdate();
			this.clearTimer();
		},
		computed: {
			...mapState(['hasLogin','userInfo','user_role']),
			checkLoginState(){
				// console.log(123,this.hasLogin)
				if(!this.hasLogin){
					uni.redirectTo({
						url:'/pages/public/wxLogin'
					})
				}
			},
			showRole:function(){
				if(this.$store.state.user_role==0){return '';}
				if(this.$store.state.user_role==1){return '老师';}
				if(this.$store.state.user_role==2){return '学生';}
				if(this.$store.state.user_role==3){return '爱心企业';}
			}
		},
		onShow(){
			
			this.startTimer();
			this.getCourseList();
			// this.changeLocationReal();//放到课程请求列表中，如果有再请求此接口，否则可能会因为接口顺序请求课程还未完成Object.keys(this.currentItem).length==0导致此接口不执行
			this.gateStatics()
		},
		onReady(){
			
		},
		onPageScroll(e){
			
		},
		methods: {
			navTo(){
				uni.navigateTo({
					url:'/pages/public/policy?t=sign_rule'
				})
			},
			getDate(){
			  const date = new Date();
			  // console.log(parseInt(date.getTime()/1000))
			  this.currentTimeSecond =parseInt(date.getTime()/1000);
			  // 获取时分秒，并格式化为时:分:秒的字符串
			  const hours = this.padZero(date.getHours());
			  const minutes = this.padZero(date.getMinutes());
			  const seconds = this.padZero(date.getSeconds());
			  this.updateStatus();
			  // 更新currentTime属性
			  return `${hours}:${minutes}:${seconds}`;
			},
			padZero(value) {
			      return value < 10 ? `0${value}` : value;
			},
			startTimer() {
			      // 设置每秒更新一次
			      this.timer = setInterval(() => {
			        this.current_time = this.getDate();
			      }, 1000); // 1000毫秒
			    },
			clearTimer() {
			  // 清除定时器
			  if (this.timer) {
				clearInterval(this.timer);
				this.timer = null;
			  }
			},
			async gateStatics(){
				let params = {};
				if(this.$store.state.user_role==3){
					return;
				}
				let data;
				if(this.$store.state.user_role==2){
					 data = await Api.apiCall('get', Api.apiName.course_gate_statics, params,true);
				}
				if(this.$store.state.user_role==1){
					 data = await Api.apiCall('get', Api.apiName.course_teacher_gate_statics, params,true);
				}
				if (!data ||data.code!=0) {
					return;
				}
				this.had=data.data.had;
				this.absence=data.data.absence;
			},
			async getCourseList() {
				let params = {role:this.$store.state.user_role};
				let data = await Api.apiCall('get', Api.apiName.course_order_today, params,true);
				if (!data || data.data.arr.length==0) {
					return;
				}
				this.course_range = data.data.arr;
				
				if(this.course_section_selected==0){
					 this.currentItem = this.course_range[0];
					 this.course_section_selected = this.currentItem['value'];
				}else{
					 this.currentItem = this.course_range.find(obj => obj.value == this.course_section_selected);
				}
				this.changeLocationReal()
			},
			initParam(){
				this.sign_current='非签到时间'
			},
			changeCourse(e){
				this.currentItem = this.course_range.find(obj => obj.value == e);
				//切换课程时恢复初始值
				this.initParam()
			},
			
			changeLocationReal(){
						
				// if(!this.hasLogin){
				// 	console.log('未登录不更新位置');
				// 	return;
				// }
				let that=this;
				if(Object.keys(this.currentItem).length==0){
					return;
				}
				uni.startLocationUpdate({
					success:res=>{
						uni.onLocationChange(function(rel){
							that.distence = that.distanceBetweenCoordinates(that.currentItem.campus_info.latitude, that.currentItem.campus_info.longitude, rel.latitude, rel.longitude)
							that.updateColor();
							
						})
					},
					fail:err=>console.error('开启小程序接收位置消息失败：', err),
					complete: msg => {
						console.log('调用开启小程序接收位置消息 API 完成');
						
					}
				})
			},
		
			
			signClick(){
				if(!this.is_entrance_range){this.$api.msg(`请进入签到范围签到`);return;}
				if(!this.is_duration){this.$api.msg(`当前不在签到时间内`);return;}
				let that = this;
				uni.showModal({
					title:'确认进行上课签到？',
				    content: '确认签到后，签到时间不能更改',
				    success: async (e)=>{
				    	if(e.confirm){
				    		let params = {c_id:that.currentItem.course_id,s_id:that.currentItem.value,role:that.$store.state.user_role};
							
				    		// console.log(params);return;
							let data = await Api.apiCall('post', Api.apiName.course_sign, params);
				    		if (!data || !data.data) {
				    			return;
				    		}
							that.$api.msg(`签到成功`);
				    		setTimeout(function(){
								that.getCourseList();
								that.gateStatics()
							},1500)
				    	}
				    }
				});
				
				
			},
			//更新圆圈颜色和下方签到范围文字
			updateColor(){
				// 模拟距离
				// this.distence-=109800;
				// console.log('距离',this.distence,'范围',this.currentItem.campus_info.pouch_distance)
				if(this.distence>this.currentItem.campus_info.pouch_distance){
					this.entrance_tip='未进入签到范围';
					this.is_entrance_range=false;
					return;
				}
				this.entrance_tip='已进入签到范围';
				this.is_entrance_range=true;
				return;
			},
			updateStatus(){
				if(Object.keys(this.currentItem).length==0){
					return;
				}
				let item = this.currentItem;
				// 每章节只打一次卡，上课前30分钟至上课结束后15分钟内，期间都可以打卡
				// currentTimeSecond当前时间搓
				if(this.currentTimeSecond>=(item.begin-30*60)&&this.currentTimeSecond<=(item.end+15*60)){
					this.sign_current='上课签到';
					this.is_duration=true;
				}else{
					this.sign_current='非签到时间';
					this.is_duration=false;
				}
			},
			toRadians(degrees) {
			  return degrees * Math.PI / 180;
			},
			distanceBetweenCoordinates(lat1, lon1, lat2, lon2) {
			  var earthRadiusKm = 6371;
			
			  var dLat = this.toRadians(lat2 - lat1);
			  var dLon = this.toRadians(lon2 - lon1);
			
			  var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
			          Math.cos(this.toRadians(lat1)) * Math.cos(this.toRadians(lat2)) *
			          Math.sin(dLon/2) * Math.sin(dLon/2);
			  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
			  var distance =parseInt(earthRadiusKm * c *1000);
			
			  return distance;
			}
		},
	

	}
</script>

<style lang="scss">	

	page {
		background: #F5F5F5;
		
	}
	.dis-flex{
		background: #FFFFFF;
		display: flex;
		flex-direction: row;
		margin: 40rpx;
		border-radius: 20rpx;
		padding: 30rpx;
		font-size: 24rpx;
		align-items: center;
	}
	.dis-two-flex{
		display: flex;
		flex-direction: row;
		margin: 40rpx;
		justify-content: center;
	}
	.turn-s{
		background: #FFFFFF;
		display: flex;
		padding: 30rpx;
		width: 50%;
		border-radius: 20rpx;
		margin: 0rpx 8rpx;
		font-size: 26rpx;
	}
	.flex1{
		flex: 1;
	}
	.user-name{
		font-size: 28rpx;
		font-weight: 600;
	}
	.user-info{
		display: flex;
		flex: 1;
		align-items: center;
	}
	.user-role{
		border-radius: 16rpx;
		padding: 10rpx 20rpx;
		background: rgba(48, 133, 173, 0.15);
		margin-left: 20rpx;
	}
	.today{
		flex: 1;
		margin-left: 10rpx;
		height: 76rpx;
		line-height: 76rpx;
		font-size: 28rpx;
	}
	.course-name{
		display: flex;
		align-items: center;
	}
	.uni-select{
		border: none !important;
		// width: 340rpx !important;
		height: 76rpx !important;
		min-width: 422rpx;
		text-align: right;
		width: 422rpx !important;
		padding: 30rpx 0rpx !important;
	}
	.uni-select__input-box{
		width: 100%;
	}
	.uni-select__input-text{
		white-space: normal !important;
		overflow: visible !important;
		text-overflow: inherit !important;
		-o-text-overflow:inherit !important;
		text-align: left;
	}
	.uni-icons{
		padding-left: 10rpx;
	}
	.uni-select__input-placeholder{
		color:#999999 !important;
		text-align: right;
	}
	.uni-select__selector{
		left: 32rpx !important;
		top:calc(100% + 38rpx) !important ;
	}
	.uni-select__selector-item{
		font-size: 24rpx !important;
	}
	.uni-select__selector-item{
		border-bottom: 1px solid rgba(17,42,53,0.07);
		text-align: left !important;
	}
	.sign-column{
		display: flex;
		width: 100%;
		padding: 24rpx;
		background: #E0EDF3;
		margin-top: 60rpx;
		border-radius: 20rpx;
	}
	.sign-color{
		color: rgba(0,0, 0, 0.4);
	}
	.yuan{
		width: 260rpx;
		height: 260rpx;
		border-radius: 50%;
		margin-top: 60rpx;
		background: #C5C6C6;
		position: relative;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.activeColor{
		background: #0191FF;
	}
	.sign-current{
		// position: absolute;
		// top: 34%;
		// left: 72rpx;
		margin-top: -50rpx;
		font-size: 30rpx;
		font-weight: 600;
		color: #FFFFFF;
	}
	.sign-current-time{
		position: absolute;
		top: 60%;
		left: 72rpx;
		font-size: 28rpx;
		color: #FFFFFF;
	}
	.sign-status{
		display: flex;
		width: 100%;
		padding: 24rpx;
		
	}
	.no-course{
		height: 700rpx;
		justify-content: center;
		align-items: center;
		display: flex;
		font-size: 16px;
		color: #999999;
	}
</style>
